#include <unistd.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "server.h"

int main (int argc, char *argv[])
{
	int s_sockfd, c_sockfd;
	struct sockaddr_in s_addr;
	fd_set read_fds, test_fds;
	int fd, read_result;

	s_sockfd = socket (AF_INET, SOCK_STREAM, 0);

	s_addr.sin_family = AF_INET;
	s_addr.sin_addr.s_addr = htonl (INADDR_ANY);
	s_addr.sin_port = htons (SERVER_PORT);

	bind(s_sockfd, (struct sockaddr*) &s_addr, sizeof (s_addr));

	listen(s_sockfd, 5);

	FD_ZERO (&read_fds);
	FD_SET (s_sockfd, &read_fds);

	while (1){
		test_fds = read_fds;
		select (FD_SETSIZE, &test_fds, NULL, NULL, NULL);

		for (fd = 0; fd < FD_SETSIZE; fd++)
		{
			if ( !FD_ISSET(fd, &test_fds))
				continue;

			if ( fd == s_sockfd)
			{
				c_sockfd = accept(s_sockfd, NULL, NULL);
				FD_SET(c_sockfd, &read_fds);
			}
			else
			{
				ioctl(fd, FIONREAD, &read_result);
				if ( read_result == 0)
				{
					close(fd);
					FD_CLR(fd, &read_fds);
				}
			      else
			       	{
					service_dispatch(fd);
				}
			}
		}
	}
}
